let { User, Message } = require('../model');
const auth = require('../utils/auth');

let index_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    console.log(username);
    let obj = {
        username: username
    }
    ctx.render('novalContent.html', obj);
}

let post_fn = async (ctx, next) => {
    let input = ctx.request.body.input || '';
    let userId = ctx.session.userId;
    let msg = await Message.create({
        fromUserId: userId,
        content: input
    });

    let data = JSON.stringify(msg);
    console.log(input);
    ctx.body = { code: 200, data, msg: "发表成功！" }
}

let login_fn = async (ctx, next) => {
    ctx.render('login.html');
}

let register_fn = async (ctx, next) => {
    ctx.render('register.html');
}

let loginDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || '';
    let password = ctx.request.body.passwords || '';
    console.log(username);
    console.log(password);
    let res;
    await User.findOne({
        where: {
            username: username,
            password: password
        }
    }).then((row) => {
        let user = JSON.stringify(row);
        let u2 = JSON.parse(user);
        console.log(user);
        console.log(u2);

        if (user !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.userName = row.username;
            res = { code: 200, msg: 'Login successful' };
        } else {
            res = { code: 1000, msg: 'Incorrect username or password. Please try again' };
        }
    });
    ctx.body = res;
}

let registerDone_fn = async (ctx, next) => {

    let username = ctx.request.body.username || '';
    let passwords = ctx.request.body.passwords || '';
    let surePasswords = ctx.request.body.surePasswords || '';
    console.log(username);
    console.log(passwords);
    console.log(surePasswords);
    if (username.length > 0 && passwords.length > 0 && surePasswords.length > 0 && passwords === surePasswords) {
        let userData = await User.findOne({ where: { username: username } });
        console.log(JSON.stringify(userData));
        let res = '';
        if (userData) {
            res = { code: 8000, msg: 'The current user name is registered!' };
        } else {
            User.create({
                username: username,
                password: passwords
            });
            res = { code: 200, msg: 'Registration successful!' };
        }
        ctx.body = JSON.stringify(res);
    } else {
        console.log('Passwords are not equal. Please try again！');
    }

}

let logout_fn = async (ctx, next) => {
    ctx.session= null;
    ctx.body = { code: 200, msg: '注销成功！' }
}

module.exports = {
    '/': ['get', auth, index_fn],
    '/login': ['get', auth, login_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/post': ['post', post_fn],
    '/logout': ['post', logout_fn]
}